package com.hkts.naturalgas.base.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.naturalgas.base.entity.CalcinationPurificationBleaching;
import com.hkts.naturalgas.base.entity.CalcinationPurifyWetElectricity;
import com.hkts.naturalgas.base.entity.RoastingPurificationBleaching;
import com.hkts.naturalgas.base.entity.RoastingPurifyWetElectricity;
import com.hkts.naturalgas.base.service.IRoastingPurificationBleachingService;
import com.hkts.naturalgas.utils.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.omg.CORBA.Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 焙烧净化脱白
 *
 * @author yck
 * @since 2021-05-31
 */
@RestController
@RequestMapping("/instrumentdata/roastingPurificationBleaching")
public class RoastingPurificationBleachingController {
    private final Logger logger = LoggerFactory.getLogger(RoastingPurificationBleachingController.class);

    @Autowired
    public IRoastingPurificationBleachingService iRoastingPurificationBleachingService;

    /**
     * 分页查询数据
     *
     * @param page                          分页信息
     * @param roastingPurificationBleaching 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getRoastingPurificationBleachingPageList")
    public Result<CustomPage> getHontUserList(Page<RoastingPurificationBleaching> page, RoastingPurificationBleaching roastingPurificationBleaching) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iRoastingPurificationBleachingService.selectPage(page, roastingPurificationBleaching)));
    }

    /**
     * 保存和修改公用的
     *
     * @param roastingPurificationBleaching 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/roastingPurificationBleachingSave")
    public Result<Object> roastingPurificationBleachingSave(RoastingPurificationBleaching roastingPurificationBleaching) {
        iRoastingPurificationBleachingService.saveOrUpdate(roastingPurificationBleaching);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/roastingPurificationBleachingGetById")
    public Result<RoastingPurificationBleaching> roastingPurificationBleachingGetById(String id) {
        RoastingPurificationBleaching byId = iRoastingPurificationBleachingService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/roastingPurificationBleachingDelete")
    public Result<Object> hontUserDelete(String id) {
        iRoastingPurificationBleachingService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/roastingPurificationBleachingBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iRoastingPurificationBleachingService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }
    /** 功能描述:
     *  遍历文件 将数据导入数据库
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-02 18:04
     * @Description //TODO
     */
    @PostMapping("/importByFiles")
    public Result<Object> importByFiles(String url) throws Exception {
        File file=new File(url);
        File[] files=file.listFiles();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<files.length;i++){
            File nextfile=  files[i];
            System.out.println(nextfile.getName());
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(nextfile));
            HSSFSheet sheet = wb.getSheetAt(0);
            List<RoastingPurificationBleaching> list=new ArrayList<RoastingPurificationBleaching>(24);
            for (int j=3;j  >= 2&&j<27; j ++) {
                HSSFRow row1 = sheet.getRow(j);
                RoastingPurificationBleaching bleaching=new RoastingPurificationBleaching();
                bleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                System.out.println(row1.getCell(0).getDateCellValue());
                Date dateCellValue = row1.getCell(0).getDateCellValue();
                if(dateCellValue==null){
                    continue;
                }
                bleaching.setTime(dateCellValue.toInstant()
                        .atZone( ZoneId.systemDefault() )
                        .toLocalDateTime());
                //焙烧脱白
                bleaching.setBsjhTe105((float)row1.getCell(5).getNumericCellValue());
                bleaching.setBsjhTe102((float)row1.getCell(2).getNumericCellValue());
                bleaching.setBsjhSidu((float)row1.getCell(10).getNumericCellValue());
                bleaching.setBsjhFan1dl((float)row1.getCell(6).getNumericCellValue());
                bleaching.setBsjhFan1sv((float)row1.getCell(7).getNumericCellValue());
                bleaching.setBsjhFan2dl((float)row1.getCell(8).getNumericCellValue());
                bleaching.setBsjhFan2sv((float)row1.getCell(9).getNumericCellValue());
                list.add(bleaching);
            }
            iRoastingPurificationBleachingService.saveBatch(list);
        }

        return ResultUtil.success("成功");
    }
    /**
     * 功能描述:
     * 净化脱白数据处理 每小时内的数据转为每分钟
     *
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-08 10:26
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/dataHndler")
    @Transactional
    public Result dataHndler() throws ParseException {
        RoastingPurificationBleaching denitration = new RoastingPurificationBleaching();
        List<RoastingPurificationBleaching> roastingDusts = iRoastingPurificationBleachingService.selectList(denitration);
        List<String> collect = roastingDusts.stream().map(RoastingPurificationBleaching::getId).collect(Collectors.toList());
        System.out.println("删除数据");
        iRoastingPurificationBleachingService.deleteAll(collect);
        for (int i = 0; i < roastingDusts.size(); i++) {
            if (i != roastingDusts.size() - 1) {
                LocalDateTime time = roastingDusts.get(i).getTime();
                System.out.println(time);
                Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
                List<LocalDateTime> allHourse = DataHandlerUtils.getAllHourse(date);
                //根据算法得到一个小时内的所有数据
                //煅烧A风机电流
                List<Float> bsjhFan1dl = BezierPoint.getData(roastingDusts.get(i).getBsjhFan1dl(), roastingDusts.get(i + 1).getBsjhFan1dl());
                //煅烧A风机频率
                List<Float> bsjhFan1sv = BezierPoint.getData(roastingDusts.get(i).getBsjhFan1sv(), roastingDusts.get(i + 1).getBsjhFan1sv());
                //煅烧B风机电流
                List<Float> bsjhFan2dl = BezierPoint.getData(roastingDusts.get(i).getBsjhFan2dl(), roastingDusts.get(i + 1).getBsjhFan2dl());
                //煅烧B风机频率
                List<Float> bsjhFan2sv = BezierPoint.getData(roastingDusts.get(i).getBsjhFan2sv(), roastingDusts.get(i + 1).getBsjhFan2sv());
                List<Float> bsjhSidu = BezierPoint.getData(roastingDusts.get(i).getBsjhSidu(), roastingDusts.get(i + 1).getBsjhSidu());
                /*List<Float> bsjhSidu2 = BezierPoint.getData(roastingDusts.get(i).getBsjhSidu2(), roastingDusts.get(i + 1).getBsjhSidu2());*/
                List<Float> bsjhTe102 = BezierPoint.getData(roastingDusts.get(i).getBsjhTe102(), roastingDusts.get(i + 1).getBsjhTe102());
                List<Float> bsjhTe105 = BezierPoint.getData(roastingDusts.get(i).getBsjhTe105(), roastingDusts.get(i + 1).getBsjhTe105());

                //进行循环处理
                List<RoastingPurificationBleaching> list = new ArrayList<RoastingPurificationBleaching>();
                for (int j = 0; j < bsjhFan1dl.size(); j++) {
                    if (j == 0) {
                        roastingDusts.get(i).setBsjhFan1dl(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhFan1dl()));
                        roastingDusts.get(i).setBsjhFan1sv(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhFan1sv()));
                        roastingDusts.get(i).setBsjhSidu(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhSidu()));
                        roastingDusts.get(i).setBsjhTe102(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhTe102()));
                        /*roastingDusts.get(i).setBsjhSidu2(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhSidu2()));*/
                        roastingDusts.get(i).setBsjhTe105(DataHandlerUtils.getRundomFloatOne(roastingDusts.get(i).getBsjhTe105()));
                        roastingDusts.get(i).setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(roastingDusts.get(i));
                    } else {
                        RoastingPurificationBleaching roastingPurificationBleaching = new RoastingPurificationBleaching();
                        roastingPurificationBleaching.setBsjhFan1dl(bsjhFan1dl.get(j));
                        roastingPurificationBleaching.setBsjhFan1sv(bsjhFan1sv.get(j));
                        roastingPurificationBleaching.setBsjhFan2dl(bsjhFan2dl.get(j));
                        roastingPurificationBleaching.setBsjhFan2sv(bsjhFan2sv.get(j));
                        roastingPurificationBleaching.setBsjhTe105(bsjhTe105.get(j));
                        roastingPurificationBleaching.setBsjhTe102(bsjhTe102.get(j));
                        /*roastingPurificationBleaching.setBsjhSidu2(bsjhSidu2.get(j));*/
                        roastingPurificationBleaching.setBsjhSidu(bsjhSidu.get(j));
                        roastingPurificationBleaching.setTime(allHourse.get(j));
                        roastingPurificationBleaching.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                        list.add(roastingPurificationBleaching);
                    }

                }
                iRoastingPurificationBleachingService.saveBatch(list);
            } else {
                iRoastingPurificationBleachingService.save(roastingDusts.get(i));
            }
        }
        return ResultUtil.success("处理成功！");
    }
   /** 功能描述:
   *焙烧脱白
   * @return:
   * @Author: 杨春科
   * @Date: 2021-06-10 14:09
   * @Description //TODO
   */
   @PostMapping("/importData")
   public Result<Object> importData(String url) throws Exception {
       File file=new File(url);
       SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

       HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
       HSSFSheet sheet = wb.getSheetAt(0);
       List<RoastingPurificationBleaching> list=new ArrayList<RoastingPurificationBleaching>(2000);
       for (int j=1;j  >= 1&&j<=sheet.getLastRowNum(); j ++) {
           HSSFRow row1 = sheet.getRow(j);
           RoastingPurificationBleaching bleachin=new RoastingPurificationBleaching();
           bleachin.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
           Date dateCellValue = row1.getCell(0).getDateCellValue();
           System.out.println(dateCellValue);
           bleachin.setTime(dateCellValue.toInstant()
                   .atZone( ZoneId.systemDefault() )
                   .toLocalDateTime());
           //煅烧脱白塔出口湿度
           row1.getCell(1).setCellType(CellType.STRING);
           bleachin.setBsjhFan1dl(Float.parseFloat (row1.getCell(1).getStringCellValue()));
           row1.getCell(2).setCellType(CellType.STRING);
           bleachin.setBsjhFan1sv(Float.parseFloat (row1.getCell(2).getStringCellValue()));
           row1.getCell(3).setCellType(CellType.STRING);
           bleachin.setBsjhFan2dl(Float.parseFloat (row1.getCell(3).getStringCellValue()));
           row1.getCell(4).setCellType(CellType.STRING);
           bleachin.setBsjhFan2sv(Float.parseFloat (row1.getCell(4).getStringCellValue()));
           row1.getCell(5).setCellType(CellType.STRING);
           bleachin.setBsjhSidu(Float.parseFloat (row1.getCell(5).getStringCellValue()));
           row1.getCell(6).setCellType(CellType.STRING);
           bleachin.setBsjhSidu2(Float.parseFloat (row1.getCell(6).getStringCellValue()));
           row1.getCell(7).setCellType(CellType.STRING);
           bleachin.setBsjhTe102(Float.parseFloat (row1.getCell(7).getStringCellValue()));
           row1.getCell(8).setCellType(CellType.STRING);
           bleachin.setBsjhTe105(Float.parseFloat (row1.getCell(8).getStringCellValue()));
           list.add(bleachin);
       }
       iRoastingPurificationBleachingService.saveBatch(list);
       return ResultUtil.success("成功");
   }

    /** 功能描述:
     *根据时间将数据补全 所有值全为0
     * @return:
     * @Author: 杨春科
     * @Date: 2021-06-17 10:49
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addData")
    @Transactional
    public Result<java.lang.Object> addData(String beginDate, String endDate) throws ParseException {
        List<LocalDateTime> allMinites = DataHandlerUtils.getAllMinites(beginDate, endDate);
        List<RoastingPurificationBleaching> calcinations =new ArrayList<RoastingPurificationBleaching>();
        for(int i=0;i<allMinites.size();i++){
            RoastingPurificationBleaching bleachin=new RoastingPurificationBleaching();
            bleachin.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
            bleachin.setTime(allMinites.get(i));
            bleachin.setBsjhTe102(DataHandlerUtils.electricDataHandler(27f));
            bleachin.setBsjhFan1dl(-0.1f);
            bleachin.setBsjhFan2sv(38f);
            bleachin.setBsjhSidu(DataHandlerUtils.electricDataHandler(-19.48f));
            bleachin.setBsjhFan2dl(38f);
            bleachin.setBsjhFan1sv(0.9f);
            bleachin.setBsjhTe102(27f);
            bleachin.setBsjhTe105(DataHandlerUtils.electricDataHandler(27.5f));
            calcinations.add(bleachin);
        }
        iRoastingPurificationBleachingService.saveBatch(calcinations);
        return ResultUtil.success("处理成功！");
    }
    /** 功能描述:
    *
    * @return:
    * @Author: 杨春科
    * @Date: 2021-06-23 8:51
    * @Description //TODO 处理519之前数据电流和频率取错值的问题
    */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/dataHndler519")
    @Transactional
    public Result dataHndler519() throws ParseException {
        iRoastingPurificationBleachingService.dataHndler519();
        return ResultUtil.success("处理成功！");
    }
}
